namespace com.stifel.BranchMgmt
{
    using System;
    using System.Runtime.InteropServices;

    using com.stifel.Extensions.SharePointExtensions;

    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;

    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>
    [Guid( "b878e726-4919-43e2-b5c4-d499849e4c40" )]
    public class BranchManagementSiteLevelEventReceiver : SPFeatureReceiver
    {
        #region Methods

        public override void FeatureActivated( SPFeatureReceiverProperties properties )
        {
            using ( StifelBranchConfiguration_Definition o = new StifelBranchConfiguration_Definition( properties ) )
                o.Create( );

            using ( StifelNotificationSiteLevel_Definition o = new StifelNotificationSiteLevel_Definition( properties ) )
                o.Create( );

            addTimerJobDefinitions( properties );
        }

        public override void FeatureDeactivating( SPFeatureReceiverProperties properties )
        {
            removeTimerJobDefinitions( properties );

            using ( StifelNotificationSiteLevel_Definition o = new StifelNotificationSiteLevel_Definition( properties ) )
                o.Delete( );

            using ( StifelBranchConfiguration_Definition o = new StifelBranchConfiguration_Definition( properties ) )
                o.Delete( );
        }

        void addTimerJobDefinitions( SPFeatureReceiverProperties properties )
        {
            removeTimerJobDefinitions( properties );
            createAndScheduleOneTimeJob( properties );
            createAndScheduleNewDailyJob( properties );
        }

        void createAndScheduleNewDailyJob( SPFeatureReceiverProperties properties )
        {
            // schedule 1 time a day
            DateTime now = DateTime.Now;
            DateTime begin = new DateTime( now.Year, now.Month, now.Day, 0, 0, 0 );
            for ( int i = 0; i < 1; i++ )
            {
                DateTime end = begin.AddHours( 1 );
                createAndScheduleNewDailyJob( properties, string.Format( "{0}.{1}", SunsetBranchLease.JOBNAME, i ), begin, end, SunsetBranchLease.JOBTITLE, typeof( SunsetBranchLease ) );

                begin = begin.AddHours( 1 );
                end = begin.AddHours( 1 );
                createAndScheduleNewDailyJob( properties, string.Format( "{0}.{1}", SunsetHardware.JOBNAME, i ), begin, end, SunsetHardware.JOBTITLE, typeof( SunsetHardware ) );

                begin = begin.AddHours( 1 );
                end = begin.AddHours( 1 );
                createAndScheduleNewDailyJob( properties, string.Format( "{0}.{1}", SunsetTelephoneSystem.JOBNAME, i ), begin, end, SunsetTelephoneSystem.JOBTITLE, typeof( SunsetTelephoneSystem ) );
            }
        }

        void createAndScheduleNewDailyJob( SPFeatureReceiverProperties properties, string jobName, DateTime begin, DateTime end, string jobTitle, Type type )
        {
            SPJobDefinition job = ( SPJobDefinition ) Activator.CreateInstance( type, jobName, properties.GetWebApplication( ) );
            job.Title = jobTitle;

            SPDailySchedule schedule = new SPDailySchedule( );
            schedule.BeginHour = begin.Hour;
            schedule.BeginMinute = begin.Minute;
            schedule.BeginSecond = 0;
            schedule.EndHour = end.Hour;
            schedule.EndMinute = end.Minute;
            schedule.EndSecond = 59;
            job.Schedule = schedule;
            job.Update( );
        }

        void createAndScheduleOneTimeJob( SPFeatureReceiverProperties properties )
        {
            createAndScheduleOneTimeJob( properties, string.Format( "{0}.Immediate", SunsetBranchLease.JOBNAME ), SunsetBranchLease.JOBTITLE, typeof( SunsetBranchLease ) );
            createAndScheduleOneTimeJob( properties, string.Format( "{0}.Immediate", SunsetHardware.JOBNAME ), SunsetHardware.JOBTITLE, typeof( SunsetHardware ) );
            createAndScheduleOneTimeJob( properties, string.Format( "{0}.Immediate", SunsetTelephoneSystem.JOBNAME ), SunsetTelephoneSystem.JOBTITLE, typeof( SunsetTelephoneSystem ) );
        }

        void createAndScheduleOneTimeJob( SPFeatureReceiverProperties properties, string jobName, string jobTitle, Type type )
        {
            SPJobDefinition job = ( SPJobDefinition ) Activator.CreateInstance( type, jobName, properties.GetWebApplication( ) );
            job.Title = jobTitle;

            SPOneTimeSchedule schedule = new SPOneTimeSchedule( );
            schedule.Time = DateTime.Now.AddMinutes( 5 );
            job.Schedule = schedule;
            job.Update( );
        }

        void removeTimerJobDefinitions( SPFeatureReceiverProperties properties )
        {
            removeTimerJobDefinitions( properties, SunsetBranchLease.JOBNAME );
            removeTimerJobDefinitions( properties, SunsetHardware.JOBNAME );
            removeTimerJobDefinitions( properties, SunsetTelephoneSystem.JOBNAME );
        }

        void removeTimerJobDefinitions( SPFeatureReceiverProperties properties, string jobName )
        {
            foreach ( SPJobDefinition o in properties.GetWebApplication( ).JobDefinitions )
            {
                if ( o.Name.StartsWith( string.Format( "{0}.", jobName ), StringComparison.OrdinalIgnoreCase ) )
                    o.Delete( );
            }
        }

        #endregion Methods

        #region Other

        // Uncomment the method below to handle the event raised after a feature has been installed.
        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}
        // Uncomment the method below to handle the event raised before a feature is uninstalled.
        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}
        // Uncomment the method below to handle the event raised when a feature is upgrading.
        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}

        #endregion Other
    }
}